package com.example.xncs;


import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class AutoPlayActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private LinearLayout controlsLayout, infoLayout;
    private Button btnBack, btnPausePlay;
    private SeekBar seekBarAutoPlay;
    private TextView tvCounter, tvAutoPlayInterval, tvImageInfo, tvAppInfo;

    private FullscreenImageAdapter adapter;
    private List<String> base64ImageList;
    private List<String> imageNames;
    private Handler autoPlayHandler = new Handler();
    private Runnable autoPlayRunnable;

    private boolean isAutoPlaying = true;
    private int currentInterval = 3; // 默认3秒
    private String mode = "AUTO_PLAY"; // AUTO_PLAY 或 BROWSE

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_auto_play);

        // 获取传递的数据
        Intent intent = getIntent();
        mode = intent.getStringExtra("MODE");
        currentInterval = intent.getIntExtra("INTERVAL", 3);
        
        // 直接读取ContentProvider中的图片数据
        loadImagesFromContentProvider();

        initViews();
        setupViewPager();
        setupControls();

        if ("AUTO_PLAY".equals(mode)) {
            startAutoPlay();
        } else {
            isAutoPlaying = false;
            btnPausePlay.setText("播放");
        }

        // 隐藏系统UI
        hideSystemUI();
    }

    private void initViews() {
        viewPager = findViewById(R.id.viewPager);
        controlsLayout = findViewById(R.id.controlsLayout);
        infoLayout = findViewById(R.id.infoLayout);
        btnBack = findViewById(R.id.btnBack);
        btnPausePlay = findViewById(R.id.btnPausePlay);
        seekBarAutoPlay = findViewById(R.id.seekBarAutoPlay);
        tvCounter = findViewById(R.id.tvCounter);
        tvAutoPlayInterval = findViewById(R.id.tvAutoPlayInterval);
        tvImageInfo = findViewById(R.id.tvImageInfo);
        tvAppInfo = findViewById(R.id.tvAppInfo);

        // 设置初始间隔
        seekBarAutoPlay.setProgress(currentInterval - 1);
        tvAutoPlayInterval.setText(currentInterval + "秒");
    }

    private void setupViewPager() {
        try {
            Log.d("AutoPlayActivity", "开始设置ViewPager，base64ImageList大小: " + (base64ImageList != null ? base64ImageList.size() : "null"));
            Log.d("AutoPlayActivity", "imageNames大小: " + (imageNames != null ? imageNames.size() : "null"));
            
            // 确保数据不为空
            if (base64ImageList == null) {
                Log.e("AutoPlayActivity", "base64ImageList为null，创建空列表");
                base64ImageList = new ArrayList<>();
            }
            if (imageNames == null) {
                Log.e("AutoPlayActivity", "imageNames为null，创建空列表");
                imageNames = new ArrayList<>();
            }
            
            // 确保两个列表大小一致
            if (base64ImageList.size() != imageNames.size()) {
                Log.w("AutoPlayActivity", "base64ImageList和imageNames大小不一致，调整imageNames");
                while (imageNames.size() < base64ImageList.size()) {
                    imageNames.add("未知图片");
                }
                while (imageNames.size() > base64ImageList.size()) {
                    imageNames.remove(imageNames.size() - 1);
                }
            }
            
            adapter = new FullscreenImageAdapter(this, base64ImageList, imageNames);
            viewPager.setAdapter(adapter);
            
            Log.d("AutoPlayActivity", "ViewPager适配器设置成功");

            // 设置页面改变监听
            viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    updateImageInfo(position);

                    // 如果是自动播放模式，重置定时器
                    if (isAutoPlaying) {
                        resetAutoPlayTimer();
                    }
                }
            });

            // 初始显示第一张图片的信息
            if (!base64ImageList.isEmpty()) {
                updateImageInfo(0);
            } else {
                Log.w("AutoPlayActivity", "没有图片数据，显示默认信息");
                tvCounter.setText("0/0");
                tvImageInfo.setText("没有图片");
                tvAppInfo.setText("来自: " + getIntent().getStringExtra("APP_NAME"));
            }
            
        } catch (Exception e) {
            Log.e("AutoPlayActivity", "设置ViewPager时出错", e);
            // 显示错误信息
            tvCounter.setText("错误");
            tvImageInfo.setText("加载失败: " + e.getMessage());
            tvAppInfo.setText("请重试");
        }
    }

    private void setupControls() {
        // 返回按钮
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 播放/暂停按钮
        btnPausePlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleAutoPlay();
            }
        });

        // 间隔调节SeekBar
        seekBarAutoPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentInterval = progress + 1; // 1-21秒
                tvAutoPlayInterval.setText(currentInterval + "秒");

                if (isAutoPlaying) {
                    resetAutoPlayTimer();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        // 点击控制栏外部区域隐藏控制栏
        View.OnClickListener hideControlsListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toggleControls();
            }
        };

        // 为控制栏外的区域设置点击监听
        viewPager.setOnClickListener(hideControlsListener);
    }

    private void startAutoPlay() {
        isAutoPlaying = true;
        btnPausePlay.setText("暂停");
        resetAutoPlayTimer();
    }

    private void stopAutoPlay() {
        isAutoPlaying = false;
        btnPausePlay.setText("播放");
        autoPlayHandler.removeCallbacks(autoPlayRunnable);
    }

    private void toggleAutoPlay() {
        if (isAutoPlaying) {
            stopAutoPlay();
        } else {
            startAutoPlay();
        }
    }

    private void resetAutoPlayTimer() {
        autoPlayHandler.removeCallbacks(autoPlayRunnable);

        autoPlayRunnable = new Runnable() {
            @Override
            public void run() {
                if (isAutoPlaying && base64ImageList.size() > 1) {
                    int nextPosition = (viewPager.getCurrentItem() + 1) % base64ImageList.size();
                    viewPager.setCurrentItem(nextPosition, true);
                }
            }
        };

        autoPlayHandler.postDelayed(autoPlayRunnable, currentInterval * 1000L);
    }
    private void updateImageInfo(int position) {
        if (position < base64ImageList.size()) {
            String imageName = position < imageNames.size() ? imageNames.get(position) : "未知图片";

            tvCounter.setText((position + 1) + "/" + base64ImageList.size());
            tvImageInfo.setText(imageName);

            // 显示来源应用
            String sourceApp = getIntent().getStringExtra("APP_NAME");
            tvAppInfo.setText("来自: " + (sourceApp != null ? sourceApp : "未知应用"));
        }
    }


    private String getImageNameFromPath(String path) {
        if (path == null || path.isEmpty()) return "未知图片";
        int lastSlash = path.lastIndexOf('/');
        if (lastSlash != -1 && lastSlash < path.length() - 1) {
            return path.substring(lastSlash + 1);
        }
        return path;
    }

    /**
     * 直接从ContentProvider加载图片数据
     */
    private void loadImagesFromContentProvider() {
        Log.d("AutoPlayActivity", "开始从ContentProvider加载图片...");
        
        // 初始化列表
        base64ImageList = new ArrayList<>();
        imageNames = new ArrayList<>();
        
        try {
            Uri baseUri = Uri.parse("content://com.example.tupiancs34.provider/images");
            ContentResolver resolver = getContentResolver();

            // 请求包含base64数据的列
            String[] projection = {"_display_name", "_size", "base64_data"};
            Cursor cursor = resolver.query(baseUri, projection, null, null, null);
            
            if (cursor != null) {
                int count = cursor.getCount();
                Log.d("AutoPlayActivity", "发现 " + count + " 张图片，开始处理...");

                if (count > 0) {
                    cursor.moveToFirst();
                    int successCount = 0;
                    int failCount = 0;
                    
                    do {
                        String fileName = cursor.getString(cursor.getColumnIndex("_display_name"));
                        long fileSize = cursor.getLong(cursor.getColumnIndex("_size"));
                        String base64Data = cursor.getString(cursor.getColumnIndex("base64_data"));

                        Log.d("AutoPlayActivity", "处理图片: " + fileName + ", 大小: " + fileSize + " bytes, base64长度: " +
                                (base64Data != null ? base64Data.length() : 0));

                        // 检查是否是图片文件
                        if (fileName != null && isImageFileName(fileName) && base64Data != null && !base64Data.isEmpty()) {
                            try {
                                // 将base64字符串转换为字节数组进行验证
                                byte[] imageBytes = Base64.decode(base64Data, Base64.DEFAULT);
                                Log.d("AutoPlayActivity", "base64解码成功，字节数组长度: " + imageBytes.length);

                                // 使用BitmapFactory验证图片
                                android.graphics.BitmapFactory.Options options = new android.graphics.BitmapFactory.Options();
                                options.inJustDecodeBounds = true;
                                android.graphics.BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
                                
                                if (options.outWidth > 0 && options.outHeight > 0) {
                                    Log.d("AutoPlayActivity", "图片尺寸: " + options.outWidth + "x" + options.outHeight);
                                    
                                    // 添加到列表
                                    base64ImageList.add(base64Data);
                                    imageNames.add(fileName);
                                    successCount++;
                                    
                                    Log.d("AutoPlayActivity", "✅ 成功添加图片: " + fileName);
                                } else {
                                    Log.e("AutoPlayActivity", "❌ 无法解析图片尺寸: " + fileName);
                                    failCount++;
                                }
                            } catch (Exception e) {
                                Log.e("AutoPlayActivity", "❌ 处理图片 " + fileName + " 时出错: " + e.getMessage());
                                failCount++;
                            }
                        } else {
                            Log.d("AutoPlayActivity", "跳过非图片文件或base64数据为空: " + fileName);
                        }
                    } while (cursor.moveToNext());

                    Log.d("AutoPlayActivity", "图片处理完成 - 成功: " + successCount + ", 失败: " + failCount);
                    
                    // 显示结果
                    int finalSuccessCount = successCount;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(AutoPlayActivity.this, 
                                    "✅ 成功加载 " + finalSuccessCount + " 张图片",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Log.d("AutoPlayActivity", "没有找到图片");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(AutoPlayActivity.this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                cursor.close();
            } else {
                Log.e("AutoPlayActivity", "无法查询ContentProvider");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(AutoPlayActivity.this, "❌ 无法访问ContentProvider", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        } catch (SecurityException e) {
            Log.e("AutoPlayActivity", "权限错误: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AutoPlayActivity.this, "❌ 权限错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        } catch (Exception e) {
            Log.e("AutoPlayActivity", "加载图片时出错", e);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(AutoPlayActivity.this, "❌ 加载失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
        }
    }
    
    /**
     * 检查是否是图片文件名
     */
    private boolean isImageFileName(String fileName) {
        if (fileName == null) return false;
        String lowerCase = fileName.toLowerCase();
        return lowerCase.endsWith(".jpg") || lowerCase.endsWith(".jpeg") ||
               lowerCase.endsWith(".png") || lowerCase.endsWith(".gif") ||
               lowerCase.endsWith(".bmp") || lowerCase.endsWith(".webp");
    }

    public void toggleControls() {
        if (controlsLayout.getVisibility() == View.VISIBLE) {
            controlsLayout.setVisibility(View.GONE);
            infoLayout.setVisibility(View.GONE);
            hideSystemUI();
        } else {
            controlsLayout.setVisibility(View.VISIBLE);
            infoLayout.setVisibility(View.VISIBLE);
            showSystemUI();
        }

        // 如果是自动播放模式，控制栏显示时暂停自动隐藏
        if (isAutoPlaying) {
            autoPlayHandler.removeCallbacks(autoPlayRunnable);
            if (controlsLayout.getVisibility() == View.VISIBLE) {
                // 控制栏显示时，5秒后自动隐藏
                autoPlayHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (controlsLayout.getVisibility() == View.VISIBLE) {
                            toggleControls();
                        }
                    }
                }, 5000);
            } else {
                // 控制栏隐藏时，恢复自动播放
                resetAutoPlayTimer();
            }
        }
    }

    private void hideSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
    }

    private void showSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopAutoPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        autoPlayHandler.removeCallbacksAndMessages(null);
        
        // 清理存储的数据
        ImageDataFileManager dataManager = new ImageDataFileManager(this);
        dataManager.clearAllData();
        Log.d("AutoPlayActivity", "Cleared stored data on destroy");
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }
}
